package gui.VPOfOperations;

import entities.ProductionOrder;
import entities.RequestParameters;

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Date;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import net.miginfocom.swing.MigLayout;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

import utilities.PrintActionListener;

import javax.swing.ImageIcon;

import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.SystemColor;
import java.awt.Font;

/**
 * @author Idan
 *Report GUI
 */
public class VPOfOperationsQuantitiesBySubFamilyReport extends JPanel
{
	
	private JPanel mainPanel;
	private JScrollPane chartTableScroll;
	public DefaultTableModel model;
	private DefaultCategoryDataset dataset ;

	private VPOfOperationsTabbedPane tabbedpane;
	private JTable table;
	
	public VPOfOperationsQuantitiesBySubFamilyReport(VPOfOperationsTabbedPane myTabbedPane, RequestParameters parameters) 
	{
		setBackground(new Color(173, 216, 230));
		this.tabbedpane = myTabbedPane;
		setLayout(new MigLayout("", "[][grow][]", "[][grow][][]"));
		
		mainPanel = new JPanel(){	@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		mainPanel.setBackground(new Color(173, 216, 230));
		mainPanel.setBorder(new TitledBorder(null, "\u05D3\u05D5\u05D7 \u05D4\u05EA\u05E4\u05DC\u05D2\u05D5\u05EA \u05D9\u05D9\u05E6\u05D5\u05E8 \u05DC\u05E4\u05D9 \u05EA\u05EA \u05DE\u05E9\u05E4\u05D7\u05D4 "  + new Date(parameters.getStartTimestamp().getTime()) + " - " + new Date(parameters.getEndTimestamp().getTime()), TitledBorder.CENTER, TitledBorder.TOP, null, new Color(59, 59, 59)));
		add(mainPanel, "cell 1 1,growx,aligny center");
		mainPanel.setLayout(new MigLayout("", "[][grow]", "[][::200px][grow]"));
		
		JScrollPane scrollPane = new JScrollPane();
		mainPanel.add(scrollPane, "cell 1 1,alignx center,aligny center");
		
		table = new JTable();
		table.setFont(new Font("Tahoma", Font.PLAIN, 15));
		scrollPane.setViewportView(table);
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"\u05DB\u05DE\u05D5\u05EA", "\u05EA\u05D7\u05EA \u05DE\u05E9\u05E4\u05D7\u05D4", "\u05DE\u05E9\u05E4\u05D7\u05EA \u05DE\u05D5\u05E6\u05E8\u05D9\u05DD"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		table.getColumnModel().getColumn(1).setPreferredWidth(117);
		table.getColumnModel().getColumn(2).setPreferredWidth(121);
		table.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		
	
		
		JButton closeButton = new JButton("סגור דוח");
		closeButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
		closeButton.setIcon(new ImageIcon(VPOfOperationsQuantitiesBySubFamilyReport.class.getResource("/graphics/back.png")));
		closeButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0)
			{
				// get tab index
				tabbedpane.remove(tabbedpane.getSelectedIndex());
				// remove tab
			}
		});
		add(closeButton, "flowx,cell 1 2,alignx center");
		
		JLabel lblNewLabel = new JLabel("               ");
		add(lblNewLabel, "cell 1 2");
		
		JButton printButton = new JButton("יצא לאקסל");
		printButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
		printButton.setIcon(new ImageIcon(VPOfOperationsQuantitiesBySubFamilyReport.class.getResource("/graphics/excel.png")));
		printButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e)
			{
//JTable table = utilities.Services.parsePivotTableToJTrable(myTable);
				
				ArrayList<Object> result = utilities.Services.exportToExcel(table);
				if (result.get(0).equals(true))
				{
					// confirm
					JOptionPane.showMessageDialog(mainPanel,
							result.get(1).toString() + " :הדוח נשמר " ,"אישור",JOptionPane.INFORMATION_MESSAGE);
				}
				else
				{
					// error
					JOptionPane.showMessageDialog(mainPanel,
						    "לא ניתן לשמור את הדוח.","שגיאה",JOptionPane.ERROR_MESSAGE);
				}
				//new Thread(new PrintActionListener(mainPanel)).start();      
			}
		});
		add(printButton, "cell 1 2,alignx center");
		
		
		  
	}
	
	
	public void setVariables(ArrayList<Object> response) 
	{
		// index 0 is the flag
		// index 1 is the counter
		// index 2 and onwards is the data

		
		model = (DefaultTableModel) table.getModel();
		
		/*
		int sumOfQuantities=0;
		Float[] percentage = new Float[(int)response.get(1)];
*/
		DefaultPieDataset dataset = new DefaultPieDataset  ();
		
		 for (int i=1; i<=((int)response.get(1));i++)
	     {
			 ProductionOrder order = (ProductionOrder)response.get(i+1);
			 model.addRow(new Object[]{order.getQuantity(),order.getType(),order.getProductFamily()});
	//		 sumOfQuantities =+ order.getQuantity();
		//	 percentage[i-1] = new Float(order.getQuantity());
			 dataset.setValue(order.getType(),order.getQuantity());
			 
	     }
		 
		 /*
		 for (int j=0 ; j<percentage.length ; j++)
		 {
			 percentage[j] = percentage[j]/sumOfQuantities;
		 }

		 model.addColumn("אחוז", percentage);
	 */
		        // create Chart
		        
		 JFreeChart chart = ChartFactory.createPieChart3D(
				 ((TitledBorder)mainPanel.getBorder()).getTitle(),
				 dataset,
				 true,
				 true,
				 false);
		      
		     
		 		        
		        ChartPanel chartPanel = new ChartPanel(chart, false);
		        chartPanel.setMouseWheelEnabled(true);

		      //  chartPanel.setPreferredSize(new Dimension(500, 270));
		        
		        chartTableScroll = new JScrollPane(chartPanel);
		        mainPanel.add(chartTableScroll, "cell 1 2,grow");
		       // mainPanel.add(chartPanel, "cell 1 2,grow");
		       // chartPanel.setVisible(true);
		        

		
		
	}
	
	@Override
	public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Color color1 = getBackground();
    Color color2 = color1.darker();
    int w = getWidth();
    int h = getHeight(); 
    GradientPaint gp = new GradientPaint(
            0, 0, color1,
            0, h, color2);

    g2d.setPaint(gp);
    g2d.fillRect(0, 0, w, h);
    }
}

